package com.tstudy.laoshibang.camera;

import java.io.IOException;

import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

@SuppressWarnings("deprecation")
@SuppressLint("ViewConstructor")
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;

	public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
        	LogUtil.d("--execute surfaceCreated " + holder);
        	if (mCamera != null) {
        		 mCamera.setPreviewDisplay(holder);
                 mCamera.startPreview();
			}
        } catch (IOException e) {
        	LogUtil.d("Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
    	LogUtil.d("--execute surfaceDestroyed " + holder);
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    	LogUtil.d("--execute surfaceChanged " + holder);
        if (mHolder.getSurface() == null){
          return;
        }
        try {
        	if (mCamera != null) {
        		mCamera.stopPreview();
			}
        } catch (Exception e){
        }
        try {
			if (mCamera != null) {
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();
			}
            
        } catch (Exception e){
            LogUtil.d("Error starting camera preview: " + e.getMessage());
        }
    }
}